package com.jushu.storbox.task.tqueue;

import java.io.File;
import java.io.InputStream;
import java.util.Random;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.jushu.storbox.LoginActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.callback.IUploadCallback;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IFileDao;
import com.jushu.storbox.database.IUploadFileDao;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.UploadObject;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.manager.CatchManager;
import com.jushu.storbox.manager.UploadTaskManager;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.identity.AbsIdentity;
import com.jushu.storbox.util.identity.FileMD5Identity;
import com.jushu.storbox.util.identity.IidentityCallback;
import com.jushu.storbox.util.identity.PartFileMD5Identity;
import com.jushu.storbox.util.identity.StreamMD5FileIdentity;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.BaseUploadRequest;
import com.huawei.sharedrive.sdk.android.modelV2.request.FileSmartUploadRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.StreamUploadRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FilePreUploadResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.UploadUrlRefreshResponse;
import com.huawei.sharedrive.sdk.android.serviceV2.FileClientV2;
import com.huawei.sharedrive.sdk.android.uploadfile.FileSmartUploadV3;
import com.huawei.sharedrive.sdk.android.uploadfile.UploadCallBackV2;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public class UploadTask extends UploadPriorityTask{
	
	private final static String TAG = "UploadTask";
	private Random random;
	private int priority;
	private final String id;
	private Context context;
	private String ownerID;
	private String folderID;
	private String authorization;
	private String filePath;
	private int uploadType;
	private AbsIdentity identityTool = null;
	private FileSmartUploadV3 uploadThread = new FileSmartUploadV3();
	private boolean isCancel = false;
	private boolean isStoped = false;
	private InputStream inputStream = null;
	private String fileEncDir;
	private FileInfo fileinfo;
	private UploadObject uploadInfo;
	
	File uploadFile = null;
	
	IUploadFileDao uploadDao = null;
	IFileDao fileDao = null;
	
	BaseUploadRequest baseUploadRequest;
	
	//notifycation
	private int notificationID = -1;
	NotificationManager mNotificationManager = null;
    NotificationCompat.Builder mNotification = null;
	
	UploadCallBackV2 fileUploadCallBackV2 = new UploadCallBackV2() {
		private long oldProgress = 0;
		private long progress = 0;
		
		@Override
		public void onStart() {
			oldProgress = 0;
			progress = 0;
			uploadCallback.onStart();
			uploadInfo.setTransStatus(Constant.TRANSLATE_IS_STARTED);
			uploadInfo.notifyChange();
			uploadDao.updateUploadObject(uploadInfo);
			LogUtil.i(TAG,"upload started!");
		}

		@Override
		public void onProgres(long bytesWritten, long totalSize) {
			if (UploadTask.this.isCancel && null != uploadThread) {
				uploadThread.cancelPartsUpload();
			}
			oldProgress = bytesWritten * 100 / totalSize;
			if (11 > (int)oldProgress) {
				oldProgress = (int)oldProgress + 11; 
			} else {
				if ((int)progress != (int)oldProgress) {
					progress = oldProgress;
					uploadInfo.setTransStatus(Constant.TRANSLATE_IS_RUNNING);
					uploadInfo.setCurrentPaogress(progress);
					uploadInfo.notifyChange();
					uploadDao.updateUploadObject(uploadInfo);
					uploadCallback.onProgress((int)progress, (long)bytesWritten, totalSize);// onProgress
				}
			}
		}

		@Override
		public String getFileIdByIdentity(String identity) {
			return uploadInfo.getId();
		}

		@Override
		public boolean isHistoryRecordExist() {
			boolean result = false;
			
			if(uploadInfo == null 
					|| StringUtil.isBlank(uploadInfo.getId())
					|| uploadInfo.getTransStatus() == Constant.TRANSLATE_IS_SUCCESS){
				result = false;
			} else {
				result = true;
			}
			
			if(uploadInfo == null) {
				uploadInfo = new UploadObject();
				uploadInfo.setOwnerBy(ownerID);
				uploadInfo.setName(uploadFile.getName());
				uploadInfo.setSize(uploadFile.length());
				uploadInfo.setParent(folderID);
				uploadInfo.setLoctPath(filePath);
				uploadInfo.setTransStatus(Constant.TRANSLATE_IS_WAITING);
				uploadInfo.setType(uploadType);
				uploadInfo.setCurrentUserId(ShareDriveApplication.getInstance().getWnerID());
			}
			
			if(StringUtil.isNotBlank(uploadInfo.getIdentity())) {
				baseUploadRequest.setPrimaryIdentity(uploadInfo.getIdentity());
			}
			
			if(StringUtil.isNotBlank(uploadInfo.getExtendIdentity())) {
				baseUploadRequest.setExtenalIdentity(uploadInfo.getExtendIdentity());
			}
			
			return result;
		}
		
		@Override
		public boolean isIdentityAvaliable() {
			String identity = uploadInfo.getIdentity();
			if(StringUtil.isBlank(identity)) {
				return false;
			} else {
				return true;
			}
		}

		@Override
		public boolean computeIdentity() {
			boolean result = false;
			String identity = identityTool.computeIdentity();
			if(StringUtil.isNotBlank(identity)) {
				uploadInfo.setIdentity(identity);
				result = true;
			}
			
			try {
				if(result) {
					if(baseUploadRequest.getSize() > Constant.MD5BLOCK_KB_SIZE) {
						identityTool = new PartFileMD5Identity(filePath, 0, Constant.MD5BLOCK_KB_SIZE);
						String extenalIndetity = identityTool.computeIdentity();
						baseUploadRequest.setExtenalIdentity(extenalIndetity);
						uploadInfo.setExtendIdentity(extenalIndetity);
					} else if(baseUploadRequest.getSize() > Constant.MD5BLOCK_B_SIZE){
						identityTool = new PartFileMD5Identity(filePath, 0, Constant.MD5BLOCK_B_SIZE);
						String extenalIndetity = identityTool.computeIdentity();
						baseUploadRequest.setExtenalIdentity(extenalIndetity);
						uploadInfo.setExtendIdentity(extenalIndetity);
					}
					uploadInfo.notifyChange();
					uploadDao.updateUploadObject(uploadInfo);
					baseUploadRequest.setPrimaryIdentity(identity);
				}
			} catch(ClientException e) {
				result = false;
			}
			return result;
		}

		@Override
		public String getUploadUrlByFileId(String fileId) {
			return uploadInfo.getUploadPath();
		}

		@Override
		public void onPreUploadSuccess(FilePreUploadResponseV2 fResponse, String identity, String filePath) {
			uploadInfo.setId(fResponse.getFileId());
			uploadInfo.setUploadPath(fResponse.getUploadUrl());
			uploadInfo.setTransStatus(Constant.TRANSLATE_IS_RUNNING);
			uploadInfo.setType(uploadType);
			uploadInfo.notifyChange();
			uploadDao.updateUploadObject(uploadInfo);
		}

		@Override
		public void onSuccess(String fileID, String ownerId, FileInfoResponseV2 FileInfoResponse) {
			LogUtil.i(TAG, "[" + filePath + "]onSuccess()");
			uploadInfo.setTransStatus(Constant.TRANSLATE_IS_SUCCESS);
			uploadInfo.notifyChange();
			uploadDao.deleteFile(uploadInfo);
			UploadTaskManager.removeTask(UploadTask.this);
			FileInfoResponseV2 resposeObject = null;
			try {
				if(FileInfoResponse == null) {
					if(PublicTools.isAuthiorzationGotoTimeout(context)){
						PublicTools.reGetTokenByLoginInBanck(context);
					}
					resposeObject = FileClientV2.getInstance()
							.getFileInfo(ownerID,
									fileID, 
									ShareDriveApplication.getInstance().getAuthorization());
				} else {
					resposeObject = FileInfoResponse;
				}
				if(resposeObject != null) {
					int flag = fileDao.addIfNotExist(resposeObject);
					if(flag == 0) {
						DirectoryUtil.deleteFileThumbnailPath(context, 
								resposeObject.getOwnerBy(), resposeObject.getId(),resposeObject.getName());
					}
				} else {
					LogUtil.e(TAG,"FileClientV2 getFileInfo() is null");
				}
				uploadCallback.onSuccess(resposeObject);
			} catch (ClientException e) {
				uploadCallback.onFailure(e);
			}
		}
/**
 *  发生异常，比如中止应用，下次再进入应用时候，检查传输列表是否有东西，如果有就再次启动
 */
     //这里是上传操作失败的回调

		@Override
		public void onOperationFailure(String fileID, Throwable t) {
			LogUtil.e(TAG, "[" + filePath + "]" + t.getLocalizedMessage());
			uploadInfo.setTransStatus(Constant.TRANSLATE_IS_FAILURED);
			uploadInfo.notifyChange();
			uploadDao.updateUploadObject(uploadInfo);
			UploadTaskManager.addFailTask(UploadTask.this);
			UploadTaskManager.removeTask(UploadTask.this);
			ClientException e = null;
			if(t instanceof ClientException) {
				e = (ClientException) t;
				if(e.getStatusCode() == 0) {
					e.setStatusCode(UiConstant.TASK_TRANSLATE_FAILED);
				}
			} else {
				e = new ClientException(t);
				e.setStatusCode(UiConstant.TASK_TRANSLATE_FAILED);
			}
			uploadCallback.onFailure(e);
		}

		@Override
		public void onCancleUpload(String fileId, String ownerId) {
			UploadTaskManager.removeTask(UploadTask.this);
			uploadInfo.setTransStatus(Constant.TRANSLATE_IS_CANCELED);
			uploadInfo.notifyChange();
			uploadDao.deleteFile(uploadInfo);
		}

		@Override
		public void onCancleSuccess(String fileId, String ownerId) {
			uploadCallback.onCanceled();
		}

		@Override
		public void onCancleFail(String fileId, String ownerId) {
			uploadCallback.onCanceled();
		}

		@Override
		public void onBeginUploadPartByIndex(String fileId, String index) {
			uploadDao.updateCurrentIndex(fileId, ownerID, index);
		}

		@Override
		public void onFinishUploadPartByIndex(String fileId, String index) {
		}
		
		@Override
		public void onSuccessRefreshUploadPath(UploadUrlRefreshResponse arg0) {
			uploadInfo.setTransStatus(Constant.TRANSLATE_IS_RUNNING);
			uploadInfo.setUploadPath(arg0.getUploadUrl());
			uploadInfo.notifyChange();
			uploadDao.updateUploadObject(uploadInfo);
		}

		@Override
		public void onServerExists(String fileID, String ownerId,
				FileInfoResponseV2 FileInfoResponse) {
			LogUtil.i(TAG, "[" + filePath + "]onSuccess()");
			uploadDao.deleteFile(uploadInfo);
			UploadTaskManager.removeTask(UploadTask.this);
			try {
				if(FileInfoResponse != null) {
					int flag = fileDao.addIfNotExist(FileInfoResponse);
					if(flag == 0) {
						DirectoryUtil.deleteFileThumbnailPath(context, FileInfoResponse.getOwnerBy(), 
								FileInfoResponse.getId(), FileInfoResponse.getName());
					}
					if(fileID != null && fileID.equals(uploadInfo.getId()) ) {
						LogUtil.e(TAG,"new success fileId not equals old fileId");
					}
					uploadCallback.onProgress(100, FileInfoResponse.getSize(), FileInfoResponse.getSize());
				} else {
					LogUtil.e(TAG,"FileClientV2 getFileInfo() is null");
				}
				uploadCallback.onSuccess(FileInfoResponse);
			} catch (Exception e) {
				uploadCallback.onFailure(e);
			}
		}
		
		@Override
		public void onUploadStoped() {
			isStoped = true;
			uploadInfo.setTransStatus(Constant.TRANSLATE_IS_STOPED);
			uploadInfo.notifyChange();
			uploadInfo.setUploadTask(null);
			uploadDao.updateUploadObject(uploadInfo);
//			UploadTaskManager.addFailTask(UploadTask.this);
//			UploadTaskManager.removeTask(UploadTask.this);
			uploadCallback.onStop();
		}

	};
	
	IidentityCallback fileSha1Callback = new IidentityCallback() {
		@Override
		public void onSuccess(String identity) {
			LogUtil.i(TAG,"File MD5 Identity: " + identity);
		}
		
		@Override
		public void onStart() {
		}
		
		@Override
		public void onProgress(int currentProgress, long currentSize, long maxSize) {

		}

		@Override
		public void onFailure(Throwable t) {
			LogUtil.e(TAG, "[" + filePath + "]" + t.getLocalizedMessage());
		}
	};
	
	UploadCallbackWrapper uploadCallback = new UploadCallbackWrapper();
	
	IUploadCallback nififyCallback = new IUploadCallback() {
        
        @Override
        public void onSuccess(FileInfoResponseV2 successItem) {
            mNotification.setContentText(getResourceName()+ "  "+ context.getResources().getString(R.string.fileListadapter_upload_success));
            mNotificationManager.notify(getNotificationID(), mNotification.build());
            mNotificationManager.cancel(getNotificationID());
            uploadDao.deleteNotify(getNotificationID());
        }
        
        @Override
        public void onStart() {
            LogUtil.i(TAG, "uploadShareFile start..." + "notificationID:" + getNotificationID());
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setClass(context, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            PendingIntent p = PendingIntent.getActivity(context, 0, intent, 0);
            mNotification.setAutoCancel(false);
            mNotification.setTicker(context.getResources().getString(R.string.upload_Notification_title));
            mNotification.setContentIntent(p);
            mNotification.setContentTitle(getResourceName());
            mNotification.setProgress(100, (int) 0, false);
            mNotification.setContentText(context.getResources().getString(R.string.upload_Notification_preper_date));
            mNotificationManager.notify(getNotificationID(), mNotification.build());
        }

        @Override
        public void onProgress(int currentProgress, long currentSize, long maxSize) {
            mNotification.setContentTitle(getResourceName());
            mNotification.setProgress(100, (int) currentProgress, false);
            mNotification.setContentText(context.getResources().getString(R.string.upload_Notification_title) + "    " + (int) currentProgress + "%");
            mNotificationManager.notify(getNotificationID(), mNotification.build());
        }
        
        @Override
        public void onFailure(Throwable t) {
        	
        }

		@Override
		public void onStop() {
		}

		@Override
		public void onCanceled() {
			LogUtil.e(TAG, "uploadShareFile... onFailure:" + "notificationID:" + getNotificationID());
            mNotification.setContentText(getResourceName()+ "  "+ context.getResources().getString(R.string.fileListadapter_upload_failed));
            mNotificationManager.notify(getNotificationID(), mNotification.build());
            mNotificationManager.cancel(getNotificationID());
            uploadDao.deleteNotify(getNotificationID());
		}

		@Override
		public void onDettach() {
            mNotification.setContentText(getResourceName()+ "  "+ context.getResources().getString(R.string.fileListadapter_upload_failed));
            mNotificationManager.notify(getNotificationID(), mNotification.build());
            mNotificationManager.cancel(getNotificationID());
            uploadDao.deleteNotify(getNotificationID());
		}
    };
    
    
	public UploadTask(Context context, String folderID,
			String filePath, IUploadCallback uploadCallback) {
		this(context,ShareDriveApplication.getInstance().getWnerID(),folderID,filePath,uploadCallback);
	}
	//Common Upload
	public UploadTask(Context context, String ownerId, String folderID,
			String filePath, IUploadCallback uploadCallback) {
		this(context,ownerId,folderID,filePath,Constant.UPLOAD_TYPE_COMMON,uploadCallback);
	}
	
	public UploadTask(Context context, UploadObject uploadInfo, IUploadCallback uploadCallback) {
		
		id = uploadInfo.getLoctPath();
		
		initUploadTask(context, 
				uploadInfo.getOwnerBy(), 
				uploadInfo.getParent(), 
				uploadInfo.getLoctPath(), 
				uploadType, uploadCallback);
		this.uploadInfo = uploadInfo;

    	uploadInfo.setTransStatus(Constant.TRANSLATE_IS_WAITING);
    	uploadInfo.notifyChange();
    	uploadDao.updateUploadObject(uploadInfo);
        CatchManager.getInstance().putUploadObject(uploadInfo);
	}
	
	public UploadTask(Context context, String ownerId, String folderID,
			String filePath, int uploadType, IUploadCallback uploadCallback) {
		id = filePath;
		
		initUploadTask(context, 
				ownerId, 
				folderID, 
				filePath, 
				uploadType, uploadCallback);
        
       	uploadInfo = uploadDao.getUploadFile(ownerId, folderID, filePath);
        if(null == uploadInfo){
        	Log.i(TAG, "first Upload file");
        	uploadInfo = new UploadObject();
        	uploadInfo.setOwnerId(ownerId);
        	uploadInfo.setParent(folderID);
        	uploadInfo.setLoctPath(filePath);
        	uploadInfo.setSize(uploadFile.length());
        	uploadInfo.setName(uploadFile.getName());
        	uploadInfo.setTransStatus(Constant.TRANSLATE_IS_WAITING);
			uploadInfo.setType(uploadType);
        	uploadDao.insertFile(uploadInfo);
        } else {
        	Log.i(TAG, "history Upload file");
        }

        CatchManager.getInstance().putUploadObject(uploadInfo);
	}
	
	private void initUploadTask(Context context, String ownerId, String folderID,
			String filePath, int uploadType, IUploadCallback uploadCallback) {
		fileinfo = new FileInfo();
		random = new Random();
		this.priority = Math.abs(random.nextInt() % 10);
		this.context = context;
		this.ownerID = ownerId;
		this.folderID = folderID;
		this.authorization = ShareDriveApplication.getInstance().getAuthorization();
		this.filePath = filePath;
		this.isCancel = false;
		this.inputStream = null;
		File file = new File(filePath);
		fileinfo.setName(file.getName());
		fileinfo.setParent(folderID);
		fileinfo.setLoctPath(filePath);
		if(uploadCallback != null) {
			this.uploadCallback.registerCallback(uploadCallback);
		}
		this.uploadType = uploadType;

		uploadFile = new File(filePath);
		
		uploadDao = DAOFactory.instance(context).getUploadFileDao();
		fileDao = DAOFactory.instance(context).getFileDao();
		
		//init notification manager
        this.uploadCallback.registerCallback(nififyCallback);
		Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClass(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        PendingIntent p1 = PendingIntent.getActivity(context, 0, intent, 0);
		mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotification = new NotificationCompat
        		.Builder(context)
        		.setSmallIcon(R.drawable.icon_logo)
        		.setContentTitle(getResourceName())
        		.setContentText(context.getResources().getString(R.string.upload_Notification_title));
        mNotification.setSmallIcon(R.drawable.icon_logo);
        mNotification.setContentTitle(context.getResources().getString(R.string.stor_box_get_data) + getResourceName());
        mNotification.setAutoCancel(false);
        mNotification.setContentIntent(p1);
        mNotification.setProgress(100, 100, true);
        mNotificationManager.notify(getNotificationID(), mNotification.build());
        uploadDao.insertNotify(getNotificationID());
	}
	
	@Deprecated
	public UploadTask(Context context, String folderID,
			String filePath, InputStream inputStream,
			IUploadCallback uploadCallback) {
		random = new Random();
		this.priority = Math.abs(random.nextInt() % 10);
//		this.id = PublicTools.getFileSha1(filePath);
		this.id = filePath;
		this.context = context;
		this.ownerID = ShareDriveApplication.getInstance().getWnerID();
		this.folderID = folderID;
		this.authorization = ShareDriveApplication.getInstance().getAuthorization();
		this.inputStream = inputStream;
		this.isCancel = false;
		this.filePath = filePath;
		
		uploadFile = new File(filePath);
		
		if(uploadCallback != null) {
			this.uploadCallback.registerCallback(uploadCallback);
		}
	}
	
	@Deprecated
	public UploadTask(Context context, String folderID,
			String filePath,  String fileEncDir, InputStream inputStream,
			IUploadCallback uploadCallback) {
		random = new Random();
		this.priority = Math.abs(random.nextInt() % 10);
//		this.id = PublicTools.getFileSha1(filePath);
		this.id = filePath;
		this.context = context;
		this.ownerID = ShareDriveApplication.getInstance().getWnerID();
		this.folderID = folderID;
		this.authorization = ShareDriveApplication.getInstance().getAuthorization();
		this.inputStream = inputStream;
		this.isCancel = false;
		this.filePath = filePath;
		this.fileEncDir = fileEncDir;
		
		uploadFile = new File(filePath);
		
		if(uploadCallback != null) {
			this.uploadCallback.registerCallback(uploadCallback);
		}
	}
	
	public void initRunEnveriment() {
		isCancel = false;
		isStoped = false;
		
		if(uploadDao == null) {
			uploadDao = DAOFactory.instance(context).getUploadFileDao();
		}
		
		if(fileDao == null) {
			fileDao = DAOFactory.instance(context).getFileDao();
		}
		
        uploadInfo.setUploadTask(this);
	}
	
	private String getResourceName() {
		return uploadFile.getName();
	}
	
	public String getId() {
		return id;
	}
	
	public String getFolderID() {
		return folderID;
	}
	
	public String getOwnerId() {
		return ownerID;
	}
	
	public String getFilePath() {
		return filePath;
	}
	
	@Override
	public int getPriority() {
		// TODO Auto-generated method stub
		return priority;
	}
	
	@Override
	public void setPriority(int priority) {
		// TODO Auto-generated method stub
		this.priority = priority;
	}
	
	@Override
	public void setTipTopPriority() {
		// TODO Auto-generated method stub
		this.priority = Integer.MAX_VALUE;
	}
	
	public void cancelUploadTask() {
		this.isCancel = true;
	}

	@Override
	public void run() {
		initRunEnveriment();
		
		try {
			if (!isCancel &&!isStoped) {
				UploadTaskManager.addRunningTask(this);
				UploadTaskManager.removeWaitingTask(this);
				if (null == inputStream) {
					LogUtil.i(TAG, "[" + filePath + "]" + " runFilePathUpload... ");
					LogUtil.i(TAG, "inputStream is null, runFilePathUpload...");
					runFilePathUpload();
				} else if (null != inputStream) {
					LogUtil.i(TAG, "[" + filePath + "]" + " runFileStreamUpload... ");
					LogUtil.i(TAG, "inputStream is not null, runFilePathUpload...");
					runFileStreamUpload();
				}
			} else if(isCancel) {
				uploadCallback.onCanceled();
			} else if(isStoped) {
				UploadTaskManager.addFailTask(UploadTask.this);
				uploadInfo.setTransStatus(Constant.TRANSLATE_IS_STOPED);
				uploadInfo.notifyChange();
				uploadDao.updateUploadObject(uploadInfo);
				uploadInfo.setUploadTask(null);
				uploadCallback.onStop();
			} else {
				uploadInfo.setTransStatus(Constant.TRANSLATE_IS_FAILURED);
				uploadInfo.notifyChange();
				uploadDao.updateUploadObject(uploadInfo);
				UploadTaskManager.addFailTask(UploadTask.this);
				UploadTaskManager.removeTask(UploadTask.this);
				ClientException e = new ClientException(UiConstant.TASK_TRANSLATE_FAILED, "file sha1 is null!");
				LogUtil.e(TAG, "[" + filePath + "]" + e.getLocalizedMessage());
				uploadCallback.onFailure(e);
			}
		} catch (Exception e) {
			uploadInfo.setTransStatus(Constant.TRANSLATE_IS_FAILURED);
			uploadInfo.notifyChange();
			uploadDao.updateUploadObject(uploadInfo);
			UploadTaskManager.addFailTask(UploadTask.this);
			UploadTaskManager.removeTask(UploadTask.this);
			e.printStackTrace();
			LogUtil.e(TAG, "[" + filePath + "]" + e.getLocalizedMessage());
			uploadCallback.onFailure(e);
		} finally {
			uploadCallback.onDettach();
			CatchManager.getInstance().removeUploadObject(uploadInfo);
		}
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result += prime * result + ((ownerID == null) ? 0 : ownerID.hashCode());
		result += prime * result + ((folderID == null) ? 0 : folderID.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		UploadTask other = (UploadTask) obj;
		if (StringUtil.isBlank(other.id) 
			|| StringUtil.isBlank(other.ownerID) 
			|| StringUtil.isBlank(other.folderID)) {
			return false;
		} else if (!id.equals(other.id)
				|| !ownerID.equals(other.ownerID)
				|| !folderID.equals(other.folderID)) {
			return false;
		}
		return true;
	}
	
	public String getFileEnDir() {
		return fileEncDir;
	}
	public void setFileEnDir(String fileEnDir) {
		this.fileEncDir = fileEnDir;
	}
	//callback
	public void setCallback(IUploadCallback callback) {
		if(callback != null) {
			this.uploadCallback.registerCallback(callback);
		}
	}
	
	public void removeCallback(IUploadCallback callback) {
		if(callback != null) {
			this.uploadCallback.unRegisterCallback(callback);
		}
	}
	
	private void runFilePathUpload() {
		identityTool = new FileMD5Identity(filePath, fileSha1Callback);
		
		baseUploadRequest = new FileSmartUploadRequestV2();
		baseUploadRequest.setAuthorization(authorization);
		baseUploadRequest.setFilePath(filePath);
		baseUploadRequest.setOwnerID(ownerID);
		baseUploadRequest.setParentId(folderID);
		
		uploadThread.setUploadRequest(baseUploadRequest);
		uploadThread.setUploadCallBack(fileUploadCallBackV2);
		uploadThread.startUpload();
	}
	
	private void runFileStreamUpload() {
		iFileManager mdmTools;
		if (null == fileEncDir || "".equals(fileEncDir)) {
			mdmTools = FileManagerFactory.getFileManager(context);
		} else {
			mdmTools = FileManagerFactory.getFileManager(context, fileEncDir);
		}
		identityTool = new StreamMD5FileIdentity(inputStream, fileSha1Callback);
		baseUploadRequest = new StreamUploadRequestV2();
		baseUploadRequest.setFileName(mdmTools.getFileName(filePath));
		baseUploadRequest.setResouce(inputStream);
		baseUploadRequest.setOwnerID(ownerID);
		baseUploadRequest.setParentId(folderID);
		baseUploadRequest.setAuthorization(authorization);
		
		uploadThread.setUploadRequest(baseUploadRequest);
		uploadThread.setUploadCallBack(fileUploadCallBackV2);
		uploadThread.startUpload();
	}

	public boolean isTaskStoped() {
		return isStoped;
	}
	
	public void stopUploadTask() {
		isStoped = true;
		uploadThread.stopUpload();
	}
	int getNotificationID() {
		if(notificationID != -1) {
			notificationID = ShareDriveApplication.getInstance().getNotificationID();
		}
		return notificationID;
	}
	void setNotificationID(int notificationID) {
		this.notificationID = notificationID;
	}
}
